package com.zx.zxojbackendquestion.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zx.zxojbackendcommon.common.ErrorCode;
import com.zx.zxojbackendcommon.constant.CommonConstant;
import com.zx.zxojbackendcommon.exception.BusinessException;
import com.zx.zxojbackendcommon.utils.SqlUtils;
import com.zx.zxojbackendmodel.dto.questionSubmit.QuestionSubmitAddRequest;
import com.zx.zxojbackendmodel.entity.QuestionSubmit;
import com.zx.zxojbackendmodel.entity.User;
import com.zx.zxojbackendmodel.enums.JudgeStatusEnum;
import com.zx.zxojbackendmodel.enums.QuestionSubmitLanguageEnum;
import com.zx.zxojbackendmodel.vo.QuestionSubmitVO;
import com.zx.zxojbackendquestion.mapper.QuestionSubmitMapper;
import com.zx.zxojbackendquestion.producer.MyMessageProducer;
import com.zx.zxojbackendquestion.service.QuestionSubmitService;
import com.zx.zxojbackendserviceclient.UserFeignClient;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author ZX
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-02-04 21:46:29
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {

    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private MyMessageProducer myMessageProducer;
//    @Resource
//    private JudgeService judgeService;

    /**
     * 提交题目
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //判断编程语言是否匹配
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(questionSubmitAddRequest.getLanguage());
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }

        QuestionSubmit questionSubmit = new QuestionSubmit();
        //封装题目提交对象
        BeanUtil.copyProperties(questionSubmitAddRequest, questionSubmit);
        //设置用户id
        questionSubmit.setUserId(loginUser.getId());
        //设置判题状态
        questionSubmit.setStatus(JudgeStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = save(questionSubmit);
        if (!save){
            //失败
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"提交题目失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        // 发送消息
        myMessageProducer.sendMessage("code_exchange", "my_routingKey", String.valueOf(questionSubmitId));

        //开启一个线程进行异步判题
//        CompletableFuture.runAsync(() -> {
//            judgeService.doJudge(questionSubmit.getId());
//        });
        return questionSubmit.getId();
    }


    /**
     * 构造查询条件
     * @param questionSubmitQueryRequest
     * @return
     */

    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitAddRequest questionSubmitQueryRequest,User loginUser) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = questionSubmitQueryRequest.getSortField(); //排序字段
        String sortOrder = questionSubmitQueryRequest.getSortOrder(); //正序还是倒序
        String language = questionSubmitQueryRequest.getLanguage();//语言
        String code = questionSubmitQueryRequest.getCode();//代码
        Long questionId = questionSubmitQueryRequest.getQuestionId(); //题目id
        Long userId = loginUser.getId(); //用户id
        // 拼接查询条件
        queryWrapper.eq(QuestionSubmitLanguageEnum.getEnumByValue(language) != null, "language", language);
        queryWrapper.like(StringUtils.isNotBlank(code), "code", code);
        queryWrapper.like(StringUtils.isNotBlank(code), "code", code);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    /**
     * 获取查询包装类
     * @param questionSubmit
     * @param request
     * @return
     */

    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser, HttpServletRequest request) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //进行脱敏
        //登录用户id
        Long userId = loginUser.getId();
        if(!userFeignClient.isAdmin(loginUser) && !userId.equals(questionSubmit.getUserId()) ){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    /**
     * 分页查询题目包装
     * @param questionSubmitPage
     * @param request
     * @return
     */

    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser,HttpServletRequest request) {
        //分页题目数组
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            return getQuestionSubmitVO(questionSubmit, loginUser, request);
        }).collect(Collectors.toList());

        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




